//
//  SSUserToken.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/7/29.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit

class SSUserToken: NSObject, NSCoding {
    // 用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    // access_token的生命周期，单位是秒数。
    var expires_in: NSNumber?
    // access_token的生命周期，日期格式。
    var expire_date: NSDate {
        return NSDate(timeIntervalSinceNow: (expires_in?.doubleValue)!)
    }
    // 当前授权用户的UID
    var uid: String?
    // 用户信息
    lazy var userInfo = SSUserInfo()
    
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    override var description: String {
        let dict = dictionaryWithValuesForKeys(["access_token", "expires_in", "expire_date", "uid", "userInfo"])
    return "\(dict)"
    }
    
    /// 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
    }
    
    /// 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid") as? String
    }

    private static let filePath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userToken.plist")
    
    /// 保存token
    func saveToken() {
        NSKeyedArchiver.archiveRootObject(self, toFile: SSUserToken.filePath)
    }
    // 相当于缓存
    private static var userToken: SSUserToken?
    /// 读取token
    class func loadToken() -> SSUserToken? {
        // 缓存无内容
        if userToken == nil {
            userToken = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? SSUserToken
        }
        
        // 判断expiredate是否过期
        if userToken?.expire_date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            return nil
        }
        return userToken
    }
}
